# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import os
import re
import time

from django.db.models.loading import get_model
from wenlincms import template

from mainsys.settings import STATIC_ROOT
from wlapps.utils.base62 import wldecode
from wlapps.utils.sys_info import sys_information

register = template.Library()

"""本文件放一些基础 template_tags"""


# 获取静态文件的最后修改时间的过滤器
@register.filter(name="file_time_stamp")
def file_time_stamp(value):
    """
    在 js/css 后面添加最后修改时间的时间戳，如：  /js/c.js -> /js/c.js?fmts=1289377595.3
    如果没找取对应的文件，则直接返回原value
    """
    if value[0] == "/":
        value = value[1:]
    fn = os.path.join(STATIC_ROOT, value.replace("/", os.sep))
    if os.path.isfile(fn):
        ts = time.strftime('%m%d%H%M%S', time.localtime(os.stat(fn).st_mtime))
        value = "%s?v=%s" % (value, ts)
    return value


# 获取并更新文章浏览次数
@register.as_tag
def show_views(info, app):
    try:
        pk_st = info.split('/')[2].split('-')[0]
        pk = wldecode(pk_st, addcrc=True)
        app_name, model_name = app.split(".")
        cmod = get_model(app_name, model_name)
        the_objs = cmod.objects.filter(id=pk)
        if len(the_objs):
            the_obj = the_objs[0]
            new_data = {'view_count': the_obj.view_count + 1}
            cmod.objects.filter(id=pk).update(**new_data)
            return the_obj.view_count
        else:
            return 10
    except Exception:
        return 10


# 如果为空，则显示为“未知”等
@register.filter(name="wlweizhi")
def wlweizhi(v, i=0):
    dic = ['未知', '-', '暂无', '不限', '**', '', ]
    if v == '' or v == 'None' or v is None:
        return dic[i]
    else:
        return v


# 渲染多选类型
@register.filter(name="wlmultichoice")
def wlmultichoice(v, u):
    """
    u为具体的选项tuple变量，写法为：appname.choicename，选项变量以_choice结尾，放在app里的models.py里
    """
    if isinstance(v, list):
        v = ",".join(v)  # 修复多选类型的bug，使用了multichoice后，默认得到是列表
    try:
        vlist = v.split(',')
        if len(vlist):
            appname = u.split(".")[0]
            choicename = u.split(".")[1]
            the_model = __import__("wlapps." + appname + ".models", globals(), locals(), [choicename + "_choice"], -1)
            choice = dict(getattr(the_model, choicename + "_choice"))
            result = '未知'
            for vl in vlist:
                if len(vl):
                    if result == '未知':
                        result = choice[vl]
                    else:
                        result = result + ', ' + choice[vl]
            return result
        else:
            return '未知'
    except Exception:
        return v


# 根据当前详情页的url重新获取对象实例，在nevercache中很有用
@register.as_tag
def reload_ins(info, ap, md):
    """
    输入参数info：request.META.PATH_INFO
    """
    pk_st = info.split('/')[2].split('-')[0]
    pk = wldecode(pk_st, addcrc=True)
    cmod = get_model(ap, md)
    the_objs = cmod.objects.filter(id=pk)
    if len(the_objs):
        return the_objs[0]


# 获取用户权限
@register.as_tag
def wl_has_perm(eduser, edperm):
    return eduser.has_perm(edperm)


# 扩展spaceless，去除block内所有空格和换行符，慎用！
@register.to_end_tag
def wlspaceless(parsed):
    parsed = re.sub(r'\s', '', parsed)
    return parsed


# 类strip，去除首尾的空白
@register.filter(name="wlstrip")
def wlstrip(v):
    try:
        return re.sub(r"^(&nbsp;)+", "", v.strip())
    except Exception:
        return v


# 渲染url类型，返回带http的全连接
@register.filter(name="wlfullurl")
def wlfullurl(v):
    if v == '' or v is None or v == 'None':
        return ''
    else:
        u = re.sub(r'^https?\:\/\/(.+)$', r'\1', v)
        return 'http://' + u


# 渲染file类型，返回文件名
@register.filter(name="wlfilename")
def wlfilename(v):
    if v.startswith('uploads'):
        a = re.sub(r'^.*?([^\/]+)\.\w+$', r'\1', v)
        b = re.sub(r'^.*?(\.\w+)$', r'\1', v)
        u = a[:30] + b if len(a) > 30 else a + b
        return u
    else:
        return v


# 简单的替换器，替换为空
@register.filter(name="wlreplace")
def wlreplace(v, s):
    return re.sub(s, '', v)


# keywords过滤器，用于meta
@register.filter(name="kwsub")
def kwsub(v):
    return re.sub(' ', ', ', v)


@register.inclusion_tag("admin/includes/sys_info.html", takes_context=True)
def sys_info(context):
    """
    管理后台首页顶部的系统信息
    """
    return sys_information()


@register.inclusion_tag("admin/includes/recent_index_head.html", takes_context=True)
def recent_index_head(context):
    """
    管理后台首页顶部的各个显示项
    """
    from django.contrib.auth.models import User
    from django.contrib.sessions.models import Session
    from django.utils import timezone
    from wlmodels.company.models import ELPost, ELGeti, ELInv, ELManager, ELModify, ELCaseDetail, ELPerson
    from wlmodels.companyplus.models import ELFinanceTax, ELHGGoodsDetail

    user_count = User.objects.all().count()
    company_count = ELPost().get_total_count()
    geti_count = ELGeti().get_total_count()
    inv_count = ELInv().get_total_count()
    manager_count = ELManager().get_total_count()
    modify_count = ELModify().get_total_count()
    case_count = ELCaseDetail().get_total_count()
    tax_count = ELFinanceTax().get_total_count()
    hg_count = ELHGGoodsDetail().get_total_count()
    person_count = ELPerson().get_total_count()
    login_session_count = Session.objects.filter(expire_date__gt=timezone.now()).count()
    return {"user_count": user_count, "company_count": company_count, "tax_count": tax_count, "hg_count": hg_count,
            "geti_count": geti_count, "inv_count": inv_count, "manager_count": manager_count, "modify_count": modify_count,
            "case_count": case_count, "person_count": person_count, "login_session_count": login_session_count}


# 判断系统是否启用了文件系统缓存
@register.as_tag
def candelcache():
    from wlapps.utils.cache import candelcache
    return candelcache()
